package publishsubscribe;

import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import config.RabbitMqConnection;
import org.junit.Test;

/**
 * @description: 消息发布者（提供者）,Publish & Subscribe 模式，一个 exchange 对应多个 queue，queue 又对应多个 consumer
 * @author:刘腾辉
 * @create:2020/10/20 9:38
 */
public class Provider {
    @Test
    public void Publish() throws Exception {

        /**
         * 1.获取连接
         */
        Connection rabbitMqConnection = RabbitMqConnection.getRabbitMqConnection();

        /**
         * 2.创建 channel
         */
        Channel channel = rabbitMqConnection.createChannel();

        /**
         * 3.创建交换机 exchange 并将队列与交换机绑定
         * 绑定可以在订阅端也可以在发布端
         */
        channel.exchangeDeclare("publish and subscribe fanout", BuiltinExchangeType.FANOUT);
        channel.queueBind("publish and subscribe queue one", "publish and subscribe fanout", "");
        channel.queueBind("publish and subscribe queue two", "publish and subscribe fanout", "");

        /**
         * 4.发布消息到 exchange
         */
        for (int i = 0;i < 10;i++){
            String msg = "publish and subscribe fanout Message "+i;
            channel.basicPublish("publish and subscribe fanout","",null,msg.getBytes());
        }

        /**
         * 4.关闭资源
         */
        System.out.println("生产者消息发布完毕!");
        channel.close();
        rabbitMqConnection.close();
    }
}
